package cn.lg.soar.system.auth.service.impl;

import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.system.auth.entity.UserCurrBind;
import cn.lg.soar.system.auth.mapper.UserCurrBindMapper;
import cn.lg.soar.system.auth.service.IUserCurrBindService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;

/**
 * UserCurrBind服务层实现
 * 租户
 * @author luguoxiang
 * @since 2022-04-30
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class UserCurrBindServiceImpl extends ServiceImpl<UserCurrBindMapper, UserCurrBind> implements IUserCurrBindService {

    @Override
    public boolean set(Map<String, Serializable> map) {
        UpdateWrapper<UserCurrBind> wrapper = Wrappers.<UserCurrBind>update()
                .eq("id", UserContext.getUserId());
        map.forEach(wrapper::set);
        boolean flag = update(wrapper);
        if (flag) {
            BindContextManager.setUserBind(get());
        }
        return flag;
    }

    @Override
    public Map<String, Object> get() {
        Map<String, Object> map = getMap(
                Wrappers.<UserCurrBind>lambdaQuery()
                        .eq(UserCurrBind::getId, UserContext.getUserId())
        );
        if (map == null) {
            map = Collections.emptyMap();
        }
        return map;
    }

    @Scheduled(cron = "0 2 4 * * ? ")
    @Override
    public void optimize() {
        baseMapper.optimize();
    }
}
